<?php

class Controller_Admin_Directory extends Controller_Admin_Template
{
	protected $template = 'admin/template';
	private $db;
	private $categories = array();
	private $itemData = array();

	protected $moduleSettings;

	private $sizes = array(
		'tiny' => array(
			'size'    => array(
				'width'  => '128',
				'height' => '128',
			),
			'options' => array(
				'method' => 'crop'
			),
		),
		'hotspot' => array(
			'size'    => array(
				'width'  => '300',
				'height' => '300',
			),
			'options' => array(
				'method' => 'inscribe'
			),
		),
		'hotmap' => array(
			'size'    => array(
				'width'  => '960',
				'height' => '600',
			),
			'options' => array(
				'method' => 'inscribe'
			),
		),
		'thumbs' => array(
			'size'    => array(
				'width'  => '140',
				'height' => '140',
			),
			'options' => array(
				'method' => 'crop'
			),
		),
		'square' => array(
			'size'    => array(
				'width'  => '280',
				'height' => '280',
			),
			'options' => array(
				'method' => 'crop',
			),
		),
		'preview' => array(
			'size'    => array(
				'width'  => '500',
			),
			'options' => array(
				'method' => 'scale',
			),
		),

	);
	private $pathImages      = 'content/directory/images/';
	private $pathHotspots      = 'content/directory/hotspots/';
	private $pathAttachments = 'content/directory/attachments/';
	private $pathVideos = 'content/directory/videos/';
	private $pathAudio = 'content/directory/music/';

	public function before()
	{
		parent::before();
		$this->db = Database::instance();
		$this->model = Model::factory('directory');
		$this->template->title = 'Directory managing';
		$this->template->content = '';
		$this->setup();

	}
	/*
		['levels'] = 1 - How many levels available in section.
		['fields']['items'] = ('name', 'date' => 'Date of event', ...) - fields in item editor.
		['images']['max'] = 3 - maximum image count per item.
		['images']['sizes'] = array('thumbs', 'fullsize') - sizes of image for this section. Creates all sizes, if not defined. "Tiny" will be created anyway for dashboard.
		['images']['keepOriginal'] = (true|false) - Keeps original image in "original" folder. Flase by default.
	*/

	private function setup()
	{
		$user = Auth::getinstance()->getIdentity();
		if ($user['role'] == 'root') {
		}
		$moduleSettings = array();

//        $moduleSettings['shop']['levels'] = 2;
//        $moduleSettings['shop']['levelRules']['0']['items']['max'] = 0;
//        $moduleSettings['shop']['levelRules']['1']['items']['max'] = 0;
//        $moduleSettings['shop']['items']['fields'] = array('name' => 'Title','text1' => 'Item description',
//            'note1'=>'Sizes(only name\'s of <a href="/admin/directory/browse/sizes/" target="_blank">preloaded sizes</a>. Use comma(,) as separator) ex: xl,xxl',
//            'note2'=>'Colors(only name\'s of <a href="/admin/directory/browse/colors/" target="_blank">preloaded images</a>. Use comma(,) as separator) ex: red,blue',
//            'price',
//            'checkbox1' => 'Retrurnable',
//            'checkbox2' => 'Show in suggest',
//            'multiselect1'=>'Please select',
//            'multiselect2'=>'Please select'
//        );
//        $moduleSettings['shop']['items']['multiselect1']['source']=array('before' => array('prev'=>'Preview','Ful3l'=>'Ful3l','Full'=>'Full','Fu2ll'=>'Fu2ll','F1ull'=>'F1ull','1Full'=>'1Full','4Full'=>'4Full'));
//        $moduleSettings['shop']['items']['multiselect2']['source']=array('before' => array('prev'=>'Preview','Ful3l'=>'Ful3l','Full'=>'Full','Fu2ll'=>'Fu2ll','F1ull'=>'F1ull','1Full'=>'1Full','4Full'=>'4Full'));
//        //ALTER TABLE `directoryItems` ADD `multiselect1` TEXT NOT NULL , ADD `multiselect2` TEXT NOT NULL , ADD `multiselect3` TEXT NOT NULL
//        $moduleSettings['shop']['items']['required'] = array('name','text1','note1','note2');
//        $moduleSettings['shop']['items']['editor'] = array('text1');
//        $moduleSettings['shop']['sorting']['items'] = true;
//        $moduleSettings['shop']['levelRules']['0']['categories']['actions'] = array('add' => true, 'edit' => true, 'delete' => false);
//        $moduleSettings['shop']['items']['images']['actions'] = array('add' => true, 'edit' => true, 'delete' => true);
//        $moduleSettings['shop']['items']['images']['sizes'] = array('shopItemPreview','shopItemViewZoomBig', 'shopItemViewZoomSmall', 'shopItemViewZoomTiny', 'shopItemRecent', 'shopItemInCart');
//        $moduleSettings['shop']['items']['images']['max'] = 3;
//        $moduleSettings['shop']['items']['images']['sorting'] = true;
//        $moduleSettings['shop']['items']['images']['fields']=array('select1' => 'Image show-mode select');
//        $moduleSettings['shop']['items']['images']['select1']['source']=array('before' => array('In item description','In shop list'));
//        if ($user['role'] == 'root') {
//            $moduleSettings['shop']['items']['actions'] = array('add' => true, 'edit' => true, 'delete' => true);
//            $moduleSettings['shop']['levelRules']['0']['categories']['actions'] = array('add' => true, 'edit' => true, 'delete' => true);
//            $moduleSettings['shop']['levelRules']['1']['categories']['actions'] = array('add' => true, 'edit' => true, 'delete' => true);
//        } else {
//            $moduleSettings['shop']['items']['actions'] = array('add' => false, 'edit' => true, 'delete' => false);
//        }

/*
		$moduleSettings['catalog']['title'] = 'Catalog title';
		$moduleSettings['catalog']['description'] = 'Description';
		$moduleSettings['catalog']['levels'] = 1;
		$moduleSettings['catalog']['items']['actions'] = array('add' => true, 'edit' => false, 'delete' => true);
		$moduleSettings['catalog']['items']['max'] = 999;
		$moduleSettings['catalog']['items']['fields'] = array('name', 'text1' => 'Content');
		$moduleSettings['catalog']['items']['images']['sizes'] = array('png');
		$moduleSettings['catalog']['items']['max'] = 3;
		$moduleSettings['catalog']['categories']['max'] = 3;
		$moduleSettings['catalog']['items']['images']['max'] = 10;
		$moduleSettings['catalog']['items']['images']['sorting'] = true;
		$moduleSettings['catalog']['items']['images']['actions'] = array('add' => true, 'edit' => true, 'delete' => true);
		$moduleSettings['catalog']['categories']['images']['max'] = 10;
		$moduleSettings['catalog']['categories']['images']['sorting'] = true;
		$moduleSettings['catalog']['categories']['images']['actions'] = array('add' => true, 'edit' => true, 'delete' => true);
		$moduleSettings['catalog']['items']['attachments']['max'] = 3;
		$moduleSettings['catalog']['items']['attachments']['fields'] = array('name' => 'Title');
		$moduleSettings['catalog']['items']['attachments']['actions'] = array('add' => true, 'edit' => true, 'delete' => true);
		$moduleSettings['catalog']['categories']['images']['max'] = 3;
		$moduleSettings['catalog']['items']['sorting'] = $moduleSettings['catalog']['categories']['sorting'] = true;
		$moduleSettings['faq']['levels'] = 0;
		$moduleSettings['faq']['title']['items'] = 'text1';
		$moduleSettings['faq']['fields']['items'] = array('text1' => 'Question', 'text2' => 'Answer');
		$moduleSettings['faq']['sorting']['items'] = true;
		$moduleSettings['faq']['images']['sizes'] = array('thumbs');
		$moduleSettings['faq']['images']['keepOriginal'] = true;
		$moduleSettings['news']['levels'] = 0;
		$moduleSettings['news']['title']['items'] = 'text1';
		$moduleSettings['news']['fields']['items'] = array('date', 'text1' => 'News');
		$moduleSettings['news']['sorting']['items'] = true;
		$moduleSettings['photogallery']['levels'] = 0;
		$moduleSettings['photogallery']['fields']['items'] = array('name' => 'Gallery title', 'text1' => 'Description');
		$moduleSettings['photogallery']['images'] = true;
		//$moduleSettings['photogallery']['actions']['items'] = array('add' => false, 'edit' => true, 'delete' => false);
		$moduleSettings['videogallery']['levels'] = 0;
		$moduleSettings['videogallery']['fields']['items'] = array('name', 'url' => 'Youtube link');
		$moduleSettings['videogallery']['sorting']['items'] = true;
		$moduleSettings['store']['levels'] = 1;
		$moduleSettings['store']['levelRules']['0']['max']['items'] = 0;
		$moduleSettings['store']['fields']['items'] = array('name' => 'Beat title', 'price');
		$moduleSettings['store']['audio'][''] = true;
		$moduleSettings['store']['sorting']['items'] = true;
		$moduleSettings['shop']['levels'] = 1;
		$moduleSettings['shop']['fields']['items'] = array('name' => 'Item title', 'price', 'text1' => 'Description', 'text2' => 'Size (one per line)');
		$moduleSettings['shop']['actions']['categories'] = array('add' => false, 'edit' => true, 'delete' => false);
		$moduleSettings['shop']['sorting']['items'] = true;
 */
		$this->moduleSettings = $moduleSettings;
	}

	private function getPermissions($itemId, $section, $recursive = true)
	{
		$itemData['permissions'] = array();
		$moduleSettings = $this->moduleSettings[$section];
		$attachments = $this->model->getAttachmentsByItem($section);
		$images = $this->model->getImagesByItem($section);
		$audio = $this->model->getAudioByItem($section);
		$videos = $this->model->getVideosByItem($section);
		$items = $this->model->getItemsByCategory($section);
		$categories = $this->model->getCategoriesByParentId($section);
		$level = 0;
		if ($itemId) {
			$item = $this->model->getItem($itemId, $section);
			if (!$item) {
				throw new ForbiddenException('Item not found');
			}
			if ($item['isCategory']) {
				$level = (string)$this->categories[$item['id']]['level'];
				if (!$recursive) {
				}
				if (isset($moduleSettings['levelRules'][$level])) {
					$moduleSettings = array_replace_recursive($moduleSettings, $moduleSettings['levelRules'][$level]);
				}
			}
		}
		if ($itemId == 0) {
			if (isset($moduleSettings['levelRules']['0'])) {
				$moduleSettings = array_replace_recursive($moduleSettings, $moduleSettings['levelRules']['0']);
			}
		}

		$itemData['stat']['count']['images'] = (isset($images[$itemId]) ? count($images[$itemId]) : 0);
		$itemData['stat']['count']['attachments'] = (isset($attachments[$itemId]) ? count($attachments[$itemId]) : 0);
		$itemData['stat']['count']['videos'] = (isset($videos[$itemId]) ? count($videos[$itemId]) : 0);
		$itemData['stat']['count']['audio'] = (isset($audio[$itemId]) ? count($audio[$itemId]) : 0);
		$itemData['stat']['count']['categories'] = (isset($categories[$itemId]) ? count($categories[$itemId]) : 0);
		$itemData['stat']['count']['items'] = (isset($items[$itemId]) ? count($items[$itemId]) : 0);
		$itemType = ((isset($item['isCategory']) ? $item['isCategory'] : true) ? 'categories' : 'items');
		$itemData['permissions']['edit'] = (isset($moduleSettings[$itemType]['actions']['edit']) ? $moduleSettings[$itemType]['actions']['edit'] : true);
		$itemData['permissions']['delete'] = (isset($moduleSettings[$itemType]['actions']['delete']) ? $moduleSettings[$itemType]['actions']['delete'] : true);
		$types = array('items', 'categories');
		$availableTypes = array('categories', 'items', 'images', 'attachments', 'videos', 'audio');
		foreach ($availableTypes as $type) {
			foreach ($moduleSettings as $values) {
				if (isset($values[$type])) {
					$types[] = $type;
					switch ($type) {
						case 'images':
						case 'attachments':
						case 'videos':
						case 'audio':
							if (isset($moduleSettings[$itemType][$type])) {
								$moduleSettings[$type] = $moduleSettings[$itemType][$type];
							}
							break;
					}
				}
			}
		}
		for ($index = 0; $index < count($types); $index++) {
			$type = $types[$index];
			$itemData['permissions'][$type]['sorting'] = isset($moduleSettings[$type]['sorting']) ? $moduleSettings[$type]['sorting'] : false;
			$defaultPermission = true;
			if ($type != 'items' && $type != 'categories') {
				$defaultPermission = false;
			}
			$itemData['permissions'][$type]['edit'] = (isset($moduleSettings[$type]['actions']['edit']) ? $moduleSettings[$type]['actions']['edit'] : $defaultPermission);
			$itemData['permissions'][$type]['delete'] = (isset($moduleSettings[$type]['actions']['delete']) ? $moduleSettings[$type]['actions']['delete'] : $defaultPermission);
			$itemData['permissions'][$type]['add'] = (isset($moduleSettings[$type]['actions']['add']) ? $moduleSettings[$type]['actions']['add'] : $defaultPermission);
			if (isset($moduleSettings['levels'])) {
				switch ($type) {
					case 'categories':
						if ($level >= $moduleSettings['levels']) {
							$itemData['permissions'][$type]['add'] = false;
						}
						break;
					case 'items':
						if ($level > $moduleSettings['levels']) {
							$itemData['permissions'][$type]['add'] = false;
						}
						break;
				}
			}
			if (isset($moduleSettings[$type]['max'])) {
				switch ($type) {
					case 'categories':
						$itemCount = (isset($categories[$itemId]) ? count($categories[$itemId]) : 0);
						break;
					case 'items':
						$itemCount = (isset($items[$itemId]) ? count($items[$itemId]) : 0);
						break;
					case 'attachments':
						$itemCount = (isset($attachments[$itemId]) ? count($attachments[$itemId]) : 0);
						break;
					case 'audio':
						$itemCount = (isset($audio[$itemId]) ? count($audio[$itemId]) : 0);
						break;
					case 'video':
						$itemCount = (isset($video[$itemId]) ? count($video[$itemId]) : 0);
						break;
					case 'images':
						$itemCount = (isset($images[$itemId]) ? count($images[$itemId]) : 0);
						break;
				}
				if ($itemCount >= $moduleSettings[$type]['max']) {
					$itemData['permissions'][$type]['add'] = false;
				}
			}
		}

		if ($recursive) {
			$itemData['subitems'] = array();
			if (isset($items[$itemId])) {
				foreach ($items[$itemId] as $subitem) {
					$itemData['subitems'][$subitem['id']] = $this->getPermissions($subitem['id'], $section, false);
				}
			}
			if (isset($categories[$itemId])) {
				foreach ($categories[$itemId] as $subitem) {
					$itemData['subitems'][$subitem['id']] = $this->getPermissions($subitem['id'], $section, false);
				}
			}
		}
		if ($recursive == false) {
			return $itemData;
		} else {
			//System::dump($itemData);
			//die();
			$this->itemData = $itemData;
			return $itemData;
		}

	}

	private function checkSection($section)
	{
		if (!isset($this->moduleSettings[$section])) {
			throw new InvalidArgumentException('Invalid section');
		}
		$categories = $this->model->getCategories($section);
		foreach ($categories as $cat) {
			$level = 1;
			$categories[$cat['id']]['level'] = $level;
			$currentParentId = $cat['parentId'];
			while($currentParentId != 0 && $level < 15) {
				if (isset($categories[$cat['parentId']])) {
					$currentParentId = $categories[$currentParentId]['parentId'];
					$level++;
				}
			}
			if ($level < 15) {
				$categories[$cat['id']]['level'] = $level;
			} else {
				$categories[$cat['id']]['level'] = 0;
			}
		}
		$this->categories = $categories;
	}

	public function actionBrowse($section, $parentId = 0)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$this->getPermissions($parentId, $section);
		if (Request::$isAjax) {
			if ('POST' == Request::$method) {
				if (isset($_POST['categories'])) {
					$action = 'categories';
				} elseif (isset($_POST['items'])) {
					$action = 'items';
				}
				if (!isset($action)) {
					$this->response->body = json_encode(array('answer' => 'error'));
					$this->response->send();
				}
				switch ($action) {
					case 'items':
						$items = $this->model->getCategoryItems($parentId, $section);
						break;
					case 'categories':
						$items = $this->model->getChidrenCategories($parentId, $section);
						break;
				}
				foreach ($_POST[$action] as $k=>$v) {
					$position = ($k + 1);
					if ($items[$v]['position'] != $position) {
						Model_Table::instance('directoryItems')->update(array('position' => $position), (int)$v);
					}
				}
				$this->autoRender = false;
				$this->response->setHeader('Content-Type', 'application/json');
				$this->response->body = json_encode(array('answer' => 'saved'));
				return;
			}
		}
//		$this->addScript('/scripts/jquery/jquery.js');
//		$this->addScript('/scripts/jquery/jquery-ui.js');
		$this->addScript('/scripts/plugin/sortable.js');
		$moduleSettings = $this->moduleSettings[$section];
		$moduleSettings['items']['fields'] = isset($moduleSettings['items']['fields']) ? $moduleSettings['items']['fields'] : array();
		$moduleSettings['categories']['fields'] = isset($moduleSettings['categories']['fields']) ? $moduleSettings['categories']['fields'] : array();
		$level = ($parentId > 0 ? (string)$this->categories[$parentId]['level'] : '0');
		if (isset($moduleSettings['levelRules'][$level])) {
			$moduleSettings = array_replace_recursive($moduleSettings, $moduleSettings['levelRules'][$level]);
		}
		$this->template->content = new View('admin/categoryIndex');
		if ($parentId) {
			$category = $this->model->getCategory($parentId, $section);
			$this->template->content->currentCategory = $category;
		} else {
			$parentId = 0;
		}
		$order    = 'name';
		$orderDir = 'ASC';
		if (in_array('date', $moduleSettings['categories']['fields']) || isset($moduleSettings['categories']['fields']['date'])) {
			$order    = 'date';
			$orderDir = 'DESC';
		}
		if (isset($moduleSettings['categories']['sorting']) ? $moduleSettings['categories']['sorting'] === true : false) {
			$order    = 'position';
			$orderDir = 'ASC';
		}
		$categories = $this->model->getChidrenCategories($parentId, $section, $order, $orderDir);
		$order    = 'name';
		$orderDir = 'ASC';
		if (isset($moduleSettings['items']['title'])) {
			$order = $moduleSettings['items']['title'];
		}
		if (in_array('date', $moduleSettings['items']['fields']) || isset($moduleSettings['items']['fields']['date'])) {
			$order    = 'date';
			$orderDir = 'DESC';
		}
		if (isset($moduleSettings['items']['sorting']) ? $moduleSettings['items']['sorting'] === true : false) {
			$order    = 'position';
			$orderDir = 'ASC';
		}
		$items      = $this->model->getCategoryItems($parentId, $section, $order, $orderDir);
		$images     = $this->model->getImages($section);
		$itemImages = array();
		foreach ($images as $image) {
			$itemImages[$image['itemId']][] = $image;
		}
		$this->template->content->parentId   = $parentId;
		$this->template->content->section    = $section;
		$this->template->content->categories = $categories;
		$this->template->content->allCategories = $this->categories;
		$this->template->content->items      = $items;
		$this->template->content->images     = $itemImages;
		$this->template->content->pathImages  = $this->pathImages;
		$this->template->content->moduleSettings = $moduleSettings;
		$this->template->content->itemData = $this->itemData;
	}

	public function actionItem($section, $itemId)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$item = $this->model->getItem($itemId, $section);
		if (!$item) {
			throw new ForbiddenException('Item not found');
		}
		$this->getPermissions($item['id'], $section);
		$moduleSettings = $this->moduleSettings[$section];
		$level = ($item['parentId'] > 0 ? (string)$this->categories[$item['parentId']]['level'] : '0');
		if (isset($moduleSettings['levelRules'][$level])) {
			$moduleSettings = array_replace_recursive($moduleSettings, $moduleSettings['levelRules'][$level]);
		}
		$images = $this->model->getItemImages($item['id'], $section, 'position', 'ASC');
		if (Request::$isAjax) {
			if ('POST' == Request::$method) {
				if (isset($_POST['images'])) {
					$action = 'images';
				}
				if (!isset($action)) {
					$this->response->body = json_encode(array('answer' => 'error'));
					$this->response->send();
				}
				switch ($action) {
					case 'images':
						$items = $images;
						break;
				}
				foreach ($_POST[$action] as $k=>$v) {
					$position = ($k + 1);
					if ($items[$v]['position'] != $position) {
						Model_Table::instance('directoryImages')->update(array('position' => $position), (int)$v);
					}
				}
				$this->autoRender = false;
				$this->response->setHeader('Content-Type', 'application/json');
				$this->response->body = json_encode(array('answer' => 'saved'));
				return;
			}
		}
//		$this->addScript('/scripts/jquery/jquery.js');
//		$this->addScript('/scripts/jquery/jquery-ui.js');
		$this->addScript('/scripts/plugin/sortable.js');
		$this->template->content = new View('admin/itemIndex');
		$videos      = $this->model->getItemVideos($item['id'], $section);
		if ($videos) {
			$this->addStyle('/styles/jquerytools/overlay.css');
//			$this->addScript('/scripts/jquery/jquery.js');
//			$this->addScript('/scripts/jquerytools/jquery.tools.min.js');
			$this->addScript('/scripts/plugin/player.js');
		}
		$attachments = $this->model->getItemAttachments($item['id'], $section);
		$audio = $this->model->getItemAudio($item['id'], $section);
		$this->template->content->section          = $section;
		$this->template->content->item             = $item;
		$this->template->content->images           = $images;
		$this->template->content->videos           = $videos;
		$this->template->content->pathVideos       = '/' . $this->pathVideos;
		$this->template->content->attachments      = $attachments;
		$this->template->content->audio            = $audio;
		$this->template->content->pathAttachments  = $this->pathAttachments;
		$this->template->content->pathAudio        = $this->pathAudio;
		$this->template->content->backUrl          = Request::$controller . 'browse/' . $section  . '/' . $item['parentId'] . '/';
		$this->template->content->moduleSettings = $moduleSettings;
		$this->template->content->itemData = $this->itemData;
	}



	public function actionHotspots($section, $imageId)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$image = $this->model->getImage($imageId, $section);
		$item = $this->model->getItem($image['itemId'], $section);
		if (!$item) {
			throw new ForbiddenException('Item not found');
		}
		$this->getPermissions($item['id'], $section);
		$moduleSettings = $this->moduleSettings[$section];
		$level = ($item['parentId'] > 0 ? (string)$this->categories[$item['parentId']]['level'] : '0');
		if (isset($moduleSettings['levelRules'][$level])) {
			$moduleSettings = array_replace_recursive($moduleSettings, $moduleSettings['levelRules'][$level]);
		}
		$hotspots = $this->model->getImageHotspots($image['id'], $section, 'position', 'ASC');
		if (Request::$isAjax) {
			if ('POST' == Request::$method) {
				if (isset($_POST['hotspots'])) {
					$action = 'hotspots';
				}
				if (!isset($action)) {
					$this->response->body = json_encode(array('answer' => 'error'));
					$this->response->send();
				}
				switch ($action) {
					case 'hotspots':
						$items = $hotspots;
						break;
				}
				foreach ($_POST[$action] as $k=>$v) {
					$position = ($k + 1);
					if ($items[$v]['position'] != $position) {
						Model_Table::instance('directoryHotspots')->update(array('position' => $position), (int)$v);
					}
				}
				$this->autoRender = false;
				$this->response->setHeader('Content-Type', 'application/json');
				$this->response->body = json_encode(array('answer' => 'saved'));
				return;
			}
		}
//		$this->addScript('/scripts/jquery/jquery.js');
//		$this->addScript('/scripts/jquery/jquery-ui.js');
		$this->addScript('/scripts/plugin/sortable.js');
		$this->addScript('/scripts/swfobject.js');
		$this->template->content = new View('admin/hotspotIndex');
		$this->template->content->section          = $section;
		$this->template->content->image            = $image;
		$this->template->content->item             = $item;
		$this->template->content->hotspots         = $hotspots;
		$this->template->content->pathHotspots       = '/' . $this->pathHotspots;
		$this->template->content->backUrl          = Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/';
		$this->template->content->moduleSettings = $moduleSettings;
		$this->template->content->itemData = $this->itemData;
	}


	public function actionAddCategory($section, $categoryId = 0)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$category = $this->model->getCategory($categoryId, $section);
		if (!$category && $categoryId != 0) {
			throw new InvalidArgumentException('Invalid category ID.');
		} else {
			$this->actionEditItem($section, null, $categoryId, 1);
		}
	}

	public function actionEditCategory($section, $categoryId = 0)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$category = $this->model->getCategory($categoryId, $section);
		if (!$category && $categoryId != 0) {
			throw new InvalidArgumentException('Invalid category ID.');
		} else {
			$this->actionEditItem($section, $categoryId, null, 1);
		}
	}

	public function actionAddItem($section, $categoryId = 0)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$category = $this->model->getCategory($categoryId, $section);
		if (!$category && $categoryId != 0) {
			throw new InvalidArgumentException('Invalid category ID.');
		} else {
			$this->actionEditItem($section, null, $categoryId);
		}
	}

	public function actionEditItem($section, $id, $categoryId = null, $isCategory = 0)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$level = 0;
		if ($id) {
			$item = $this->model->getItem($id, $section);
			if (!$item) {
				throw new ForbiddenException('Item not found.');
			}
			$parentId = $item['parentId'];
			$isCategory = $item['isCategory'];
			$level = ($item['parentId'] > 0 ? (string)$this->categories[$item['parentId']]['level'] : '0');
		}
		if ($categoryId) {
			$level = (string)$this->categories[$categoryId]['level'];
		}
		$moduleSettings = $this->moduleSettings[$section];
		if (isset($moduleSettings['levelRules'][$level])) {
			$moduleSettings = array_replace_recursive($moduleSettings, $moduleSettings['levelRules'][$level]);
		}
		$this->template->content = new View('admin/form');
		$this->template->content->section = $section;
		$this->template->content->title = 'Add new item';
		$type = ($isCategory ? 'categories' : 'items');
		$fields = isset($moduleSettings[$type]['fields']) ? $moduleSettings[$type]['fields'] : array();
		$form = new Form('item');
		$form->labelWidth = '120px';
		if ((in_array('name', $fields) || isset($fields['name'])) || !count($fields)) {
			$form->text('name', (isset($fields['name'])? $fields['name'] : 'Name'))
				->attribute('size', 40)
				->rule('maxLength', 128);
		}
		if (in_array('date', $fields) || isset($fields['date'])) {
			$form->text('date', (isset($fields['date'])? $fields['date'] : 'Date'))
                ->rule('date')
				->rule('maxLength', 10)
				->attribute('class', 'DatePicker')
				->attribute('size', 20);
//			$this->addScript('/scripts/jquery/jquery.js');
//			$this->addScript('/scripts/jquery/jquery-ui.js');
			$this->addScript('/scripts/jquery/timepicker/timepicker.js');
			$this->addScript('/scripts/plugin/datepicker.js');
			$this->addLink(array(
				'href' => '/styles/jquery-ui/ui-custom/jquery-ui.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
		}

        for ($cnt = 1; $cnt <= 3; $cnt++) {
            if (in_array('multiselect'.$cnt,$fields) || isset($fields['multiselect'.$cnt])) {
                $select = array();
                $settings = $moduleSettings[$type]['multiselect' . $cnt]['source'];
                if (isset($settings['before'])) {
                    $select = $settings['before'];
                }
                if (isset($settings['query'])) {
                    $source = $this->db->query($settings['query'])->fetchAll();
                    $key = (isset($settings['value']) ? $settings['value'] : 'id');
                    $value = (isset($settings['name']) ? $settings['name'] : 'name');
                    if ($source) {
                        foreach ($source as $row) {
                            $select[$row[$key]] = $row[$value];
                        }
                    } else {
                        $formError = isset($settings['message']) ? $settings['message'] : 'Error in select' . $cnt . ' field.';
                    }
                }
                $form->multiselect('multiselect'.$cnt,$select, (isset($fields['multiselect'.$cnt])? $fields['multiselect'.$cnt] : 'Select'))
                    ->attribute('class', 'multiselect');
//                $this->addScript('/scripts/multiselect/jquery.min.js');
//                $this->addScript('/scripts/multiselect/jquery-ui.min.js');
                $this->addScript('/scripts/multiselect/jquery.localisation-min.js');
                $this->addScript('/scripts/multiselect/jquery.scrollTo-min.js');
                $this->addScript('/scripts/multiselect/ui.multiselect.js');
                $this->addScript('/scripts/multiselect/settings.js');
            }
        }
		if (in_array('dateTime', $fields) || isset($fields['time'])) {
			$form->text('dateTime', (isset($fields['time'])? $fields['time'] : 'Date and Time'))
                ->rule('datetime')
				->attribute('size', 40)
				->attribute('class', 'TimePicker')
				->rule('maxLength', 64);
//			$this->addScript('/scripts/jquery/jquery.js');
//			$this->addScript('/scripts/jquery/jquery-ui.js');
			$this->addScript('/scripts/jquery/timepicker/timepicker.js');
			$this->addScript('/scripts/plugin/timepicker.js');
			$this->addLink(array(
				'href' => '/styles/jquery-ui/ui-custom/jquery-ui.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
		}

		for ($cnt = 1; $cnt <= 3; $cnt++) {
			if (in_array('note' . $cnt, $fields) || isset($fields['note' . $cnt])) {
				$form->text('note' . $cnt, (isset($fields['note1'])? $fields['note' . $cnt] : 'Note'))
					->attribute('size', 40)
					->rule('maxLength', 64);
			}
		}
		for ($cnt = 1; $cnt <= 3; $cnt++) {
			if ((in_array('select' . $cnt, $fields) || isset($fields['select' . $cnt]))) {
				$select = array();
				$settings = $moduleSettings[$type]['select' . $cnt]['source'];
				if (isset($settings['before'])) {
					$select = $settings['before'];
				}
				if (isset($settings['query'])) {
					$source = $this->db->query($settings['query'])->fetchAll();
					$key = (isset($settings['value']) ? $settings['value'] : 'id');
					$value = (isset($settings['name']) ? $settings['name'] : 'name');
					if ($source) {
						foreach ($source as $row) {
							$select[$row[$key]] = $row[$value];
						}
					} else {
						$formError = isset($settings['message']) ? $settings['message'] : 'Error in select' . $cnt . ' field.';
					}
				}
				$form->select('select' . $cnt, $select, (isset($fields['select' . $cnt])? $fields['select' . $cnt] : '&nbsp;'));
			}
		}
		for ($cnt = 1; $cnt <= 3; $cnt++) {
			if (in_array('checkbox' . $cnt, $fields) || isset($fields['checkbox' . $cnt])) {
				$form->checkbox('checkbox' . $cnt, '', (isset($fields['checkbox' . $cnt])? $fields['checkbox' . $cnt] : '&nbsp;'));
			}
		}
		if (in_array('address', $fields) || isset($fields['address'])) {
			$form->text('address', (isset($fields['address'])? $fields['address'] : 'Address'))
				->attribute('size', 40)
				->rule('maxLength', 64);
		}
		if (in_array('phone', $fields) || isset($fields['phone'])) {
			$form->text('phone', (isset($fields['phone'])? $fields['phone'] : 'Phone'))
				->attribute('size', 40)
				->rule('maxLength', 64);
		}
		if (in_array('email', $fields) || isset($fields['email'])) {
			$form->text('email', (isset($fields['email'])? $fields['email'] : 'E-mail'))
				->attribute('size', 40)
				->rule('maxLength', 64)
				->rule('email');
		}
		if (in_array('url', $fields) || isset($fields['url'])) {
			$form->text('url', (isset($fields['url'])? $fields['url'] : 'URL'))
				->attribute('size', 40)
				->rule('maxLength', 64)
				->rule('url');
		}
		if (in_array('price', $fields) || isset($fields['price'])) {
			$form->text('price', (isset($fields['price'])? $fields['price'] : 'Price (USD)'))
				->attribute('size', 10)
				->rule('maxLength', 10)
				->rule('float');
		}
		$settings = isset($moduleSettings[$type]['editor']);
		if ($settings) {
//			$this->addScript('/scripts/jquery/jquery.js');
//			$this->addScript('/scripts/jquery/markitup.js');
//			$this->addScript('/scripts/jquery/jquery-ui.js');
			$this->addScript('/scripts/elrte/elrte.min.js');
			$this->addScript('/scripts/plugin/editor.js');
			$this->addLink(array(
				'href' => '/styles/jquery-ui/ui-custom/jquery-ui.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
			$this->addLink(array(
				'href' => '/styles/elrte/elrte.full.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
		}
		for ($cnt = 1; $cnt <= 3; $cnt++) {
			if (in_array('text' . $cnt, $fields) || isset($fields['text' . $cnt])) {
				$settings = isset($moduleSettings[$type]['editor']) ? $moduleSettings[$type]['editor'] : array();
				if (in_array('text' . $cnt, $settings)) {
					$form->html('insert', '', '<img src="/images/icons/paste.png" width="273" heigth="63" alt="Paste icon" style="vertical-align:middle;"/> Paste text by clicking this button!' );
				}
				$form->textarea('text' . $cnt, (isset($fields['text' . $cnt])? $fields['text' . $cnt] : 'Description'))
					->attribute('cols', 140)->attribute('rows', 25);
				if (in_array('text' . $cnt, $settings)) {
					$form->elements['text' . $cnt]->attribute('class', 'elrte');
				}
			}
		}
		$form->submit('submit', 'Save');
		$settings = isset($moduleSettings[$type]['required']) ? $moduleSettings[$type]['required'] : array();
		if (count($settings)) {
			foreach ($settings as $field) {
				if (isset($form->elements[$field])) {
					$form->elements[$field]->rule('required');
				}
			}
		}
		if ($id) {
			$this->template->content->title = 'Add new item';
			$form->loadValues($item);
		}
		if (Request::$method == 'POST') {
			if ($form->validate()) {
				$alias = Url::safe((isset($form->elements['name']) ? $form->elements['name']->value : ''));
				$alias = $alias != '' ? $alias : $section;
				$getNewAlias = false;
				if ($id) {
					$itemAlias = substr($item['alias'], 0, strrpos($item['alias'], '-'));
					$itemAlias = $itemAlias ? $itemAlias : $item['alias'];
				} else {
					$getNewAlias = true;
				}
				if (($id !== null ? ($itemAlias != $alias) : false)) {
					if (is_numeric(substr($item['alias'], strrpos($item['alias'], '-'), 1)) || substr($item['alias'], 0, strrpos($item['alias'], '-')) == '') {
						$getNewAlias = true;
					} else {
						$alias = $item['alias'];
					}
				}
				if ($getNewAlias) {
					$nextNumber = Model::factory('directory')->getNextNumber('directoryItems', $alias, $section);
					if ($nextNumber == 1) {
						if (count($this->db->query('SELECT 1 FROM `directoryItems` WHERE `alias`=?', $alias))) {
							$alias .= '-2';
						}
					} else {
						$alias = $alias . '-' . $nextNumber;
					}
				}
				if ($id) {
					$values = $form->getModified();
					if (isset($values['date'])) {
						if ($values['date'] == '') {
							$values['date'] = null;
						}
					}
					if (isset($values['dateTime'])) {
						if ($values['dateTime'] == '') {
							$values['dateTime'] = null;
						}
					}
					$values['alias'] = $alias;
					$values['parentId'] = $parentId;
					$values['section'] = $section;
//                    system::dump($values);exit();
					Model_Table::instance('directoryItems')->update($values, $id);
				} else {
					$values = $form->getValues();
					$cnt = 0;
					Model_Table::instance('directoryItems')->keys['string'] = 'token';
					while (true === Model_Table::instance('directoryItems')->exists(($token = System::random('alphanuml', 3))) && $cnt < 3) {
						$cnt++;
					}
					$values['token'] = $token;
					if (isset($values['date']) ? ($values['date'] == '') : true) {
						$values['date'] = null;
					}
					if (isset($values['dateTime'])) {
						if ($values['dateTime'] == '') {
							$values['dateTime'] = null;
						}
					}
					$values['alias'] = $alias;
					$values['parentId'] = $categoryId;
					$values['section'] = $section;
					if ($isCategory) {
						$values['isCategory'] = 1;
					}

					Model_Table::instance('directoryItems')->insert($values);
				}
				if ($id) {
					$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $id . '/');
				} else {
					$this->response->redirect(Request::$controller . 'browse/' . $section  . '/' . ($categoryId ? $categoryId . '/' : ''));
				}
			}
		}
		if (isset($item)) {
			$this->template->content->backUrl = Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/';
		} else {
			$this->template->content->backUrl = Request::$controller . 'browse/' . $section  . '/' . $categoryId . '/';
		}
		if (isset($formError)) {
		    $form = $formError;
		}
		$this->template->content->form = $form;
	}

	public function actionAddImage($section, $itemId)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$item = $this->model->getItem($itemId, $section);
		if (!$item) {
			throw new InvalidArgumentException('Invalid item ID.');
		} else {
			$this->actionEditImage($section, null, $itemId);
		}
	}

	public function actionEditImage($section, $id, $itemId = null)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$this->template->content = new View('admin/form');
		if ($id) {
			$image = $this->model->getImage($id, $section);
			$itemId = $image['itemId'];
		}
		$item = $this->model->getItem($itemId, $section);
		$moduleSettings = $this->moduleSettings[$section];
		$level = ($item['parentId'] > 0 ? (string)$this->categories[$item['parentId']]['level'] : '0');
		if (isset($moduleSettings['levelRules'][$level])) {
			$moduleSettings = array_replace_recursive($moduleSettings, $moduleSettings['levelRules'][$level]);
		}
		$type = ($item['isCategory'] ? 'categories' : 'items');
		$fields = isset($moduleSettings[$type]['images']['fields']) ? $moduleSettings[$type]['images']['fields'] : array();
		$this->template->content->section = $section;
		$this->template->content->title = 'Add new image';
		$form = new Form('image');
		if ((in_array('name', $fields) || isset($fields['name']))) {
			$form->text('name', (isset($fields['name'])? $fields['name'] : 'Name'))
				->attribute('size', 40)
				->rule('maxLength', 128);
		}
		$form->file('file', 'Image file')->attribute('size', 35)->rule('extension', array('jpg', 'jpeg', 'png', 'gif'));
		if (isset($moduleSettings[$type]['images']['editor'])) {
//			$this->addScript('/scripts/jquery/jquery.js');
//			$this->addScript('/scripts/jquery/jquery-ui.js');
			$this->addScript('/scripts/elrte/elrte.min.js');
			$this->addScript('/scripts/plugin/editor.js');
			$this->addLink(array(
				'href' => '/styles/jquery-ui/ui-custom/jquery-ui.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
			$this->addLink(array(
				'href' => '/styles/elrte/elrte.full.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
		}
		for ($cnt = 1; $cnt <= 2; $cnt++) {
			if ((in_array('select' . $cnt, $fields) || isset($fields['select' . $cnt]))) {
				$select = array();
				$settings = $moduleSettings[$type]['images']['select' . $cnt]['source'];
				if (isset($settings['before'])) {
					$select = $settings['before'];
				}
				if (isset($settings['query'])) {
					$source = $this->db->query($settings['query'])->fetchAll();
					$key = (isset($settings['value']) ? $settings['value'] : 'id');
					$value = (isset($settings['name']) ? $settings['name'] : 'name');
					if ($source) {
						foreach ($source as $row) {
							$select[$row[$key]] = $row[$value];
						}
					} else {
						$formError = isset($settings['message']) ? $settings['message'] : 'Error in select' . $cnt . ' field.';
					}
				}
				$form->select('select' . $cnt, $select, (isset($fields['select' . $cnt])? $fields['select' . $cnt] : '&nbsp;'));
			}
		}
		for ($cnt = 1; $cnt <= 2; $cnt++) {
			if (in_array('checkbox' . $cnt, $fields) || isset($fields['checkbox' . $cnt])) {
				$form->checkbox('checkbox' . $cnt, '', (isset($fields['checkbox' . $cnt])? $fields['checkbox' . $cnt] : '&nbsp;'));
			}
		}
		if (in_array('hotspots', $fields) || isset($fields['hotspots'])) {
			$form->checkbox('hotspots', '', (isset($fields['hotspots'])? $fields['hohotspotsspot'] : 'Hotspots'));
		}
		for ($cnt = 1; $cnt <= 2; $cnt++) {
			if (in_array('text' . $cnt, $fields) || isset($fields['text' . $cnt])) {
				if (isset($moduleSettings[$type]['images']['editor']) ? in_array('text' . $cnt, $moduleSettings[$type]['images']['editor']) : false) {
					$form->html('insert', '', '<img src="/images/icons/paste.png" width="273" heigth="63" alt="Paste icon" style="vertical-align:middle;"/> Paste text by clicking this button!' );
				}
				$form->textarea('text' . $cnt, (isset($fields['text' . $cnt])? $fields['text' . $cnt] : 'Description'))
					->attribute('cols', 100)->attribute('rows', 15);
				if (isset($moduleSettings[$type]['images']['editor']) ? in_array('text' . $cnt, $moduleSettings[$type]['images']['editor']) : false) {
					$form->elements['text' . $cnt]->attribute('class', 'elrte');
				}
			}
		}
		$form->submit('submit', 'Save');
		if (isset($moduleSettings[$type]['images']['required'])) {
			foreach ($moduleSettings[$type]['images']['required'] as $field) {
				if (isset($form->elements[$field])) {
					$form->elements[$field]->rule('required');
				}
			}
		}
		if ($id) {
			$this->template->content->title = 'Edit image';
			$form->loadValues($image);
		} else {
			$form->elements['file']->rule('required');
		}
		if (Request::$method == 'POST') {
			if ($form->validate()) {
				if ($id) {
					$alias = $image['alias'];
				} else {
					$cnt = 0;
					while (true === Model_Table::instance('directoryImages')->exists(($alias = System::random('alphanuml', 6))) && $cnt < 3) {
						$cnt++;
					}
				}
				if (isset($form->elements['file']->files[0])) {
					$files = $form->elements['file']->files;
					$file = $files[0];
					$umask = umask(0);
					$tmpDir = $this->pathImages . '_tmp/';
					if (!file_exists($tmpDir)) {
						mkdir($tmpDir, 0777, true);
					}
					$tmpFilename = $tmpDir . 'tmp';
					if (false === move_uploaded_file($file['tmp_name'], $tmpFilename)) {
						umask($umask);
						throw new Exception('File %s cannot be moved.');
					} else {
						$this->resizeImage($alias, $section, $item['isCategory']);
						if ((isset($moduleSettings[$type]['images']['keepOriginal']) ? $moduleSettings[$type]['images']['keepOriginal'] : false)) {
							$fileName = $this->imagePath($alias, 'original', $section);
							if (!file_exists($imageDir = $this->imageDir($alias, 'original', $section))) {
								mkdir($imageDir, 0777, true);
							}
							copy($this->pathImages . '_tmp/tmp', $fileName);
						}
					}
					list ($imgWidth, $imgHeight, $type, $attr) = getimagesize($tmpFilename);
					$resolution = $imgWidth . 'x' . $imgHeight;
				}
				if ($id) {
					$values = $form->getModified();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					if (isset($resolution)) {
						$values['resolution'] = $resolution;
					}
					Model_Table::instance('directoryImages')->update($values, $id);
				} else {
					$values = $form->getValues();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					if (isset($resolution)) {
						$values['resolution'] = $resolution;
					}
					Model_Table::instance('directoryImages')->insert($values);
				}
				$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/');
			}
		}
		$this->template->content->backUrl = Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/';
		if (isset($formError)) {
		    $form = $formError;
		}
		$this->template->content->form = $form;
	}


	public function actionAddHotspot($section, $imageId)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$image = $this->model->getImage($imageId, $section);
		if (!$imageId) {
			throw new InvalidArgumentException('Invalid image ID.');
		} else {
			$this->actionEditHotspot($section, null, $imageId);
		}
	}

	public function actionEditHotspot($section, $id, $imageId = null)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$this->template->content = new View('admin/form');
		if ($id) {
			$hotspot = $this->model->getHotspot($id, $section);
			$imageId = $hotspot['imageId'];
		}
		$image = $this->model->getImage($imageId, $section);
		$item = $this->model->getItem($image['itemId'], $section);
		$moduleSettings = $this->moduleSettings[$section];
		$level = ($item['parentId'] > 0 ? (string)$this->categories[$item['parentId']]['level'] : '0');
		if (isset($moduleSettings['levelRules'][$level])) {
			$moduleSettings = array_replace_recursive($moduleSettings, $moduleSettings['levelRules'][$level]);
		}
		$type = ($item['isCategory'] ? 'categories' : 'items');
		$fields = isset($moduleSettings[$type]['hotspots']['fields']) ? $moduleSettings[$type]['hotspots']['fields'] : array();
		$this->template->content->section = $section;
		$this->template->content->title = 'Add new hotspot';
		$form = new Form('hotspot');
		if ((in_array('name', $fields) || isset($fields['name']))) {
			$form->text('name', (isset($fields['name'])? $fields['name'] : 'Name'))
				->attribute('size', 40)
				->rule('maxLength', 128);
		}
		$form->file('file', 'Image file')->attribute('size', 35)->rule('extension', array('jpg', 'jpeg', 'png', 'gif'));
		for ($cnt = 1; $cnt <= 1; $cnt++) {
			if (in_array('text' . $cnt, $fields) || isset($fields['text' . $cnt])) {
				$form->textarea('text' . $cnt, (isset($fields['text' . $cnt])? $fields['text' . $cnt] : 'Description'))
					->attribute('cols', 100)->attribute('rows', 15);
			}
		}
		$form->submit('submit', 'Save');
		if (isset($moduleSettings[$type]['hotspots']['required'])) {
			foreach ($moduleSettings[$type]['hotspots']['required'] as $field) {
				if (isset($form->elements[$field])) {
					$form->elements[$field]->rule('required');
				}
			}
		}
		if ($id) {
			$this->template->content->title = 'Edit hotspot';
			$form->loadValues($hotspot);
		}
		if (Request::$method == 'POST') {
			if ($form->validate()) {
				if ($id) {
					$token = $hotspot['token'];
				} else {
					$cnt = 0;
					Model_Table::instance('directoryHotspots')->keys['string'] = 'token';
					while (true === Model_Table::instance('directoryHotspots')->exists(($token = System::random('alphanuml', 6))) && $cnt < 3) {
						$cnt++;
					}
				}
				if (isset($form->elements['file']->files[0])) {
					$files = $form->elements['file']->files;
					$file = $files[0];
					$umask = umask(0);
					$tmpDir = $this->pathHotspots . '_tmp/';
					if (!file_exists($tmpDir)) {
						mkdir($tmpDir, 0777, true);
					}
					$tmpFilename = $tmpDir . 'tmp';
					if (false === move_uploaded_file($file['tmp_name'], $tmpFilename)) {
						umask($umask);
						throw new Exception('File %s cannot be moved.');
					} else {
						$this->resizeHotspot($token, $section, $item['isCategory']);
						if ((isset($moduleSettings[$type]['hotspots']['keepOriginal']) ? $moduleSettings[$type]['hotspots']['keepOriginal'] : false)) {
							$fileName = $this->hotspotPath($token, 'original', $section);
							if (!file_exists($hotspotDir = $this->hotspotDir($token, 'original', $section))) {
								mkdir($hotspotDir, 0777, true);
							}
							copy($this->pathHotspots . '_tmp/tmp', $fileName);
						}
					}
					list ($imgWidth, $imgHeight, $type, $attr) = getimagesize($tmpFilename);
					$resolution = $imgWidth . 'x' . $imgHeight;
				}
				if ($id) {
					$values = $form->getModified();
					$values['token'] = $token;
					$values['imageId'] = $imageId;
					$values['section'] = $section;
					if (isset($resolution)) {
						$values['resolution'] = $resolution;
					}
					Model_Table::instance('directoryHotspots')->update($values, $id);
				} else {
					$values = $form->getValues();
					$values['token'] = $token;
					$values['imageId'] = $imageId;
					$values['section'] = $section;
					if (isset($resolution)) {
						$values['resolution'] = $resolution;
					}
					Model_Table::instance('directoryHotspots')->insert($values);
				}
				$this->response->redirect(Request::$controller . 'hotspots/' . $section  . '/' . $image['id'] . '/');
			}
		}
		$this->template->content->backUrl = Request::$controller . 'hotspots/' . $section  . '/' . $image['id'] . '/';
		if (isset($formError)) {
		    $form = $formError;
		}
		$this->template->content->form = $form;
	}


	public function actionDefineHotspot($section, $id)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$this->addScript('/scripts/swfobject.js');
		$content = $this->template->content = new View('admin/hotspotDefine');
		if ($id) {
			$hotspot = $this->model->getHotspot($id, $section);
			$imageId = $hotspot['imageId'];
		}
		$content->image = $image = $this->model->getImage($imageId, $section);
		$content->item = $item = $this->model->getItem($image['itemId'], $section);
		$content->currentId = $id;
		$moduleSettings = $this->moduleSettings[$section];
		$level = ($item['parentId'] > 0 ? (string)$this->categories[$item['parentId']]['level'] : '0');
		if (isset($moduleSettings['levelRules'][$level])) {
			$moduleSettings = array_replace_recursive($moduleSettings, $moduleSettings['levelRules'][$level]);
		}
		$type = ($item['isCategory'] ? 'categories' : 'items');
		$form = new Form('points');
		$form->hidden('points');
		if (Request::$method == 'POST') {
			if ($form->validate()) {
				$values = $form->getValues();
				Model_Table::instance('directoryHotspots')->update(array('points' => $values['points']), (int)$id);
				$this->response->redirect(Request::$controller . 'hotspots/' . $section  . '/' . $image['id'] . '/');
			}
		}
		$this->template->content->backUrl = Request::$controller . 'hotspots/' . $section  . '/' . $image['id'] . '/';
		$this->template->content->form = $form;
	}

	public function actionAddVideo($section, $itemId)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$item = $this->model->getItem($itemId, $section);
		if (!$item) {
			throw new InvalidArgumentException('Invalid item ID.');
		} else {
			$this->actionEditVideo($section, null, $itemId);
		}
	}

	public function actionEditVideo($section, $id, $itemId = null)
	{
		$this->addStyle('/styles/jquerytools/overlay.css');
//		$this->addScript('/scripts/jquery/jquery.js');
//		$this->addScript('/scripts/jquerytools/jquery.tools.min.js');
		$this->addScript('/scripts/plugin/uploadVideo.js');
		$section = strtolower($section);
		$this->checkSection($section);
		if ($id) {
			$video = $this->model->getVideo($id, $section);
			$itemId = $video['itemId'];
		}
		$item = $this->model->getItem($itemId, $section);
		$moduleSettings = $this->moduleSettings[$section];
		$level = ($item['parentId'] > 0 ? (string)$this->categories[$item['parentId']]['level'] : '0');
		if (isset($moduleSettings['levelRules'][$level])) {
			$moduleSettings = array_replace_recursive($moduleSettings, $moduleSettings['levelRules'][$level]);
		}
		$type = ($item['isCategory'] ? 'categories' : 'items');
		$fields = isset($moduleSettings[$type]['videos']['fields']) ? $moduleSettings[$type]['videos']['fields'] : array();
		$this->template->content = new View('admin/form');
		$this->template->content->section = $section;
		$this->template->content->title = 'Add new video';
		$form = new Form('video');
		if ((in_array('name', $fields) || isset($fields['name'])) || !count($fields)) {
			$form->text('name', (isset($fields['name'])? $fields['name'] : 'Name'))
				->attribute('size', 40)
				->rule('maxLength', 128);
		}
		$form->file('file', 'Video')->attribute('size', 35);
		$moduleSettings[$type]['videos']['filetypes'] = isset($moduleSettings[$type]['videos']['extensions']) ? $moduleSettings[$type]['videos']['extensions'] : array('mp4', 'avi', 'mpeg4', 'mpg', 'divx', 'wmv', 'flv');
		$form->elements['file']->rule('extension', $moduleSettings[$type]['videos']['extensions']);
		if (isset($moduleSettings[$type]['videos']['editor'])) {
//			$this->addScript('/scripts/jquery/jquery.js');
//			$this->addScript('/scripts/jquery/jquery-ui.js');
			$this->addScript('/scripts/elrte/elrte.min.js');
			$this->addScript('/scripts/plugin/editor.js');
			$this->addLink(array(
				'href' => '/styles/jquery-ui/ui-custom/jquery-ui.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
			$this->addLink(array(
				'href' => '/styles/elrte/elrte.full.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
		}
		for ($cnt = 1; $cnt <= 2; $cnt++) {
			if ((in_array('select' . $cnt, $fields) || isset($fields['select' . $cnt]))) {
				$select = array();
				$settings = $moduleSettings[$type]['images']['select' . $cnt]['source'];
				if (isset($settings['before'])) {
					$select = $settings['before'];
				}
				if (isset($settings['query'])) {
					$source = $this->db->query($settings['query'])->fetchAll();
					$key = (isset($settings['value']) ? $settings['value'] : 'id');
					$value = (isset($settings['name']) ? $settings['name'] : 'name');
					if ($source) {
						foreach ($source as $row) {
							$select[$row[$key]] = $row[$value];
						}
					} else {
						$formError = isset($settings['message']) ? $settings['message'] : 'Error in select' . $cnt . ' field.';
					}
				}
				$form->select('select' . $cnt, $select, (isset($fields['select' . $cnt])? $fields['select' . $cnt] : '&nbsp;'));
			}
		}
		for ($cnt = 1; $cnt <= 2; $cnt++) {
			if (in_array('checkbox' . $cnt, $fields) || isset($fields['checkbox' . $cnt])) {
				$form->checkbox('checkbox' . $cnt, '', (isset($fields['checkbox' . $cnt])? $fields['checkbox' . $cnt] : '&nbsp;'));
			}
		}
		for ($cnt = 1; $cnt <= 2; $cnt++) {
			if (in_array('text' . $cnt, $fields) || isset($fields['text' . $cnt])) {
				$form->textarea('text' . $cnt, (isset($fields['text' . $cnt])? $fields['text' . $cnt] : 'Description'))
					->attribute('cols', 100)->attribute('rows', 15);
				if (isset($moduleSettings[$type]['videos']['editor']) ? in_array('text' . $cnt, $moduleSettings[$type]['videos']['editor']) : false) {
					$form->elements['text' . $cnt]->attribute('class', 'elrte');
				}
			}
		}

		$form->submit('submit', 'Save')->attribute('rel', '#overlay');
		if (isset($moduleSettings[$type]['videos']['required'])) {
			foreach ($moduleSettings[$type]['videos']['required'] as $field) {
				if (isset($form->elements[$field])) {
					$form->elements[$field]->rule('required');
				}
			}
		}
		if ($id) {
			$this->template->content->title = 'Edit video';
			$form->loadValues($video);
		} else {
			$form->elements['file']->rule('required');
		}
		if (Request::$method == 'POST') {
			if ($form->validate()) {
				if ($id) {
					$alias = $video['alias'];
				} else {
					$cnt = 0;
					while (true === Model_Table::instance('directoryVideos')->exists(($alias = System::random('alphanuml', 3))) && $cnt < 3) {
						$cnt++;
					}
				}
				if (isset($form->elements['file']->files[0])) {
					$files = $form->elements['file']->files;
					$file = $files[0];
					$umask = umask(0);
					$videoDir = $this->videoDir($alias, $section);
					if (!file_exists($videoDir)) {
						mkdir($videoDir, 0777, true);
					}
					umask($umask);
					$videoPrevDir = $this->videoPrevDir($alias, $section);
					if (!file_exists($videoPrevDir)) {
						mkdir($videoPrevDir, 0777, true);
					}
					umask($umask);
					$videoFilename = $this->videoDir($alias, $section) . $alias . '.flv';
					$videoPrevFilename = $this->videoPrevDir($alias, $section) . $alias . '.jpg';
					set_time_limit(1200);
					//system('ffmpeg -y -i "' . $file['tmp_name'] . '" -ar 22050 -ab 32 -f flv "' . $videoFilename . '"');
					//system('ffmpeg -y -i "' . $file['tmp_name'] . '" -ar 22050 -ab 32 -vhook "/usr/lib/vhook/imlib2.so -x 100 -y 105 -i images/logo.png" -f flv "' . $videoFilename . '"');
					system('ffmpeg -y -i "' . $file['tmp_name'] . '" -ar 22050 -ab 32 -vhook "/usr/lib/vhook/imlib2.so -x ((W-w)-20) -y ((H-h)-20) -i images/logo.png" -f flv "' . $videoFilename . '"');
					system('ffmpeg -y -i "' . $videoFilename . '" -an -ss 00:00:01 -an -r 1 -vframes 1 -y -f image2 -s 480x360 "' . $videoPrevFilename . '"');
					Image::Watermark($videoPrevFilename, 'images/icons/playButton.gif', $this->videoPrevDir($alias, $section) . $alias . '_.jpg');
					$filesize = filesize($videoFilename);
				}
				if ($id) {
					$values = $form->getModified();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					if (isset($filesize)) {
						$values['filesize'] = $filesize;
					}
					if (isset($filename)) {
						$values['filename'] = $filename;
					}
					Model_Table::instance('directoryVideos')->update($values, $id);
				} else {
					$values = $form->getValues();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					$values['filesize'] = $filesize;
					Model_Table::instance('directoryVideos')->insert($values);
				}
				$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/');
			}
		}
		$this->template->content->backUrl = Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/';
		if (isset($formError)) {
		    $form = $formError;
		}
		$this->template->content->form = $form;
		$this->template->content->overlay = new View('admin/overlay');
	}

	public function actionAddAttachment($section, $itemId)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$item = $this->model->getItem($itemId, $section);
		if (!$item) {
			throw new InvalidArgumentException('Invalid item ID.');
		} else {
			$this->actionEditAttachment($section, null, $itemId);
		}
	}

	public function actionEditAttachment($section, $id, $itemId = null)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		if ($id) {
			$attachment = $this->model->getAttachment($id, $section);
			$itemId = $attachment['itemId'];
		}
		$item = $this->model->getItem($itemId, $section);
		$moduleSettings = $this->moduleSettings[$section];
		$level = ($item['parentId'] > 0 ? (string)$this->categories[$item['parentId']]['level'] : '0');
		if (isset($moduleSettings['levelRules'][$level])) {
			$moduleSettings = array_replace_recursive($moduleSettings, $moduleSettings['levelRules'][$level]);
		}
		$type = ($item['isCategory'] ? 'categories' : 'items');
		$fields = isset($moduleSettings[$type]['attachments']['fields']) ? $moduleSettings[$type]['attachments']['fields'] : array();
		$this->template->content = new View('admin/form');
		$this->template->content->section = $section;
		$this->template->content->title = 'Add new attachment';
		$form = new Form('attachment');
		if ((in_array('name', $fields) || isset($fields['name']))) {
			$form->text('name', (isset($fields['name'])? $fields['name'] : 'Name'))
				->attribute('size', 40)
				->rule('maxLength', 128);
		}
		$form->file('file', 'Attachment')->attribute('size', 35);
		if (isset($moduleSettings[$type]['attachments']['extensions'])) {
			$form->elements['file']->rule('extension', $moduleSettings[$type]['attachments']['extensions']);
		}
		if (isset($moduleSettings[$type]['attachments']['editor'])) {
//			$this->addScript('/scripts/jquery/jquery.js');
//			$this->addScript('/scripts/jquery/jquery-ui.js');
			$this->addScript('/scripts/elrte/elrte.min.js');
			$this->addScript('/scripts/plugin/editor.js');
			$this->addLink(array(
				'href' => '/styles/jquery-ui/ui-custom/jquery-ui.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
			$this->addLink(array(
				'href' => '/styles/elrte/elrte.full.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
		}
		for ($cnt = 1; $cnt <= 2; $cnt++) {
			if ((in_array('select' . $cnt, $fields) || isset($fields['select' . $cnt]))) {
				$select = array();
				$settings = $moduleSettings[$type]['attachments']['select' . $cnt]['source'];
				if (isset($settings['before'])) {
					$select = $settings['before'];
				}
				if (isset($settings['query'])) {
					$source = $this->db->query($settings['query'])->fetchAll();
					$key = (isset($settings['value']) ? $settings['value'] : 'id');
					$value = (isset($settings['name']) ? $settings['name'] : 'name');
					if ($source) {
						foreach ($source as $row) {
							$select[$row[$key]] = $row[$value];
						}
					} else {
						$formError = isset($settings['message']) ? $settings['message'] : 'Error in select' . $cnt . ' field.';
					}
				}
				$form->select('select' . $cnt, $select, (isset($fields['select' . $cnt])? $fields['select' . $cnt] : '&nbsp;'));
			}
		}
		for ($cnt = 1; $cnt <= 2; $cnt++) {
			if (in_array('checkbox' . $cnt, $fields) || isset($fields['checkbox' . $cnt])) {
				$form->checkbox('checkbox' . $cnt, '', (isset($fields['checkbox' . $cnt])? $fields['checkbox' . $cnt] : '&nbsp;'));
			}
		}
		for ($cnt = 1; $cnt <= 2; $cnt++) {
			if (in_array('text' . $cnt, $fields) || isset($fields['text' . $cnt])) {
				$form->textarea('text' . $cnt, (isset($fields['text' . $cnt])? $fields['text' . $cnt] : 'Description'))
					->attribute('cols', 100)->attribute('rows', 15);
				if (isset($moduleSettings[$type]['attachments']['editor']) ? in_array('text' . $cnt, $moduleSettings[$type]['attachments']['editor']) : false) {
					$form->elements['text' . $cnt]->attribute('class', 'elrte');
				}
			}
		}
		$form->submit('submit', 'Save');
		if (isset($moduleSettings[$type]['attachments']['required'])) {
			foreach ($moduleSettings[$type]['attachments']['required'] as $field) {
				if (isset($form->elements[$field])) {
					$form->elements[$field]->rule('required');
				}
			}
		}
		if ($id) {
			$this->template->content->title = 'Edit attachment';
			$form->loadValues($attachment);
		} else {
			$form->elements['file']->rule('required');
		}
		if (Request::$method == 'POST') {
			if ($form->validate()) {
				if ($id) {
					$alias = $attachment['alias'];
				} else {
					$cnt = 0;
					while (true === Model_Table::instance('directoryAttachments')->exists(($alias = System::random('alphanuml', 6))) && $cnt < 3) {
						$cnt++;
					}
				}
				if (isset($form->elements['file']->files[0])) {
					$files = $form->elements['file']->files;
					$file = $files[0];
					$umask = umask(0);
					$dir = $this->attachmentDir($alias, $section);
					if (!file_exists($dir)) {
						mkdir($dir, 0777, true);
					}
					$tmpFilename = $this->attachmentDir($alias, $section) . $file['name'];
					if (false === move_uploaded_file($file['tmp_name'], $tmpFilename)) {
						umask($umask);
						throw new Exception('File %s cannot be moved.');
					}
					$filename = $file['name'];
					$filesize = filesize($tmpFilename);
				}
				if ($id) {
					$values = $form->getModified();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					if (isset($filesize)) {
						$values['filesize'] = $filesize;
					}
					if (isset($filename)) {
						$values['filename'] = $filename;
					}
					Model_Table::instance('directoryAttachments')->update($values, $id);
				} else {
					$values = $form->getValues();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					$values['filesize'] = $filesize;
					$values['filename'] = $filename;
					Model_Table::instance('directoryAttachments')->insert($values);
				}
				$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/');
			}
		}
		$this->template->content->backUrl = Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/';
		if (isset($formError)) {
		    $form = $formError;
		}
		$this->template->content->form = $form;
	}

	public function actionAddAudio($section, $itemId)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$item = $this->model->getItem($itemId, $section);
		if (!$item) {
			throw new InvalidArgumentException('Invalid item ID.');
		} else {
			$this->actionEditAudio($section, null, $itemId);
		}
	}

	public function actionEditAudio($section, $id, $itemId = null)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		if ($id) {
			$audio = $this->model->getAttachment($id, $section);
			$itemId = $audio['itemId'];
		}
		$item = $this->model->getItem($itemId, $section);
		$moduleSettings = $this->moduleSettings[$section];
		$level = ($item['parentId'] > 0 ? (string)$this->categories[$item['parentId']]['level'] : '0');
		if (isset($moduleSettings['levelRules'][$level])) {
			$moduleSettings = array_replace_recursive($moduleSettings, $moduleSettings['levelRules'][$level]);
		}

		if ($item['isCategory']) {
			$type = 'categories';
		} else {
			$type = 'items';
		}
		$fields = isset($moduleSettings[$type]['audio']['fields']) ? $moduleSettings[$type]['audio']['fields'] : array();
		$this->template->content = new View('admin/form');
		$this->template->content->section = $section;
		$this->template->content->title = 'Add new audio file';
		$form = new Form('audio');
		if ((in_array('name', $fields) || isset($fields['name']))) {
			$form->text('name', (isset($fields['name'])? $fields['name'] : 'Name'))
				->attribute('size', 40)
				->rule('maxLength', 128);
		}
		$moduleSettings[$type]['audio']['extensions'] = isset($moduleSettings[$type]['audio']['extensions']) ? $moduleSettings[$type]['audio']['extensions'] : array('mp3');
		$form->file('file', 'Audio file')->attribute('size', 35)->rule('extension', $moduleSettings[$type]['audio']['extensions']);
		if (isset($moduleSettings[$type]['audio']['extensions'])) {
			$form->elements['file']->rule('extension', $moduleSettings[$type]['audio']['extensions']);
		}
		if (isset($moduleSettings[$type]['audio']['editor'])) {
//			$this->addScript('/scripts/jquery/jquery.js');
//			$this->addScript('/scripts/jquery/jquery-ui.js');
			$this->addScript('/scripts/elrte/elrte.min.js');
			$this->addScript('/scripts/plugin/editor.js');
			$this->addLink(array(
				'href' => '/styles/jquery-ui/ui-custom/jquery-ui.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
			$this->addLink(array(
				'href' => '/styles/elrte/elrte.full.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
		}
		for ($cnt = 1; $cnt <= 2; $cnt++) {
			if ((in_array('select' . $cnt, $fields) || isset($fields['select' . $cnt]))) {
				$select = array();
				$settings = $moduleSettings[$type]['audio']['select' . $cnt]['source'];
				if (isset($settings['before'])) {
					$select = $settings['before'];
				}
				if (isset($settings['query'])) {
					$source = $this->db->query($settings['query'])->fetchAll();
					$key = (isset($settings['value']) ? $settings['value'] : 'id');
					$value = (isset($settings['name']) ? $settings['name'] : 'name');
					if ($source) {
						foreach ($source as $row) {
							$select[$row[$key]] = $row[$value];
						}
					} else {
						$formError = isset($settings['message']) ? $settings['message'] : 'Error in select' . $cnt . ' field.';
					}
				}
				$form->select('select' . $cnt, $select, (isset($fields['select' . $cnt])? $fields['select' . $cnt] : '&nbsp;'));
			}
		}
		for ($cnt = 1; $cnt <= 2; $cnt++) {
			if (in_array('checkbox' . $cnt, $fields) || isset($fields['checkbox' . $cnt])) {
				$form->checkbox('checkbox' . $cnt, '', (isset($fields['checkbox' . $cnt])? $fields['checkbox' . $cnt] : '&nbsp;'));
			}
		}
		for ($cnt = 1; $cnt <= 2; $cnt++) {
			if (in_array('text' . $cnt, $fields) || isset($fields['text' . $cnt])) {
				$form->textarea('text' . $cnt, (isset($fields['text' . $cnt])? $fields['text' . $cnt] : 'Description'))
					->attribute('cols', 100)->attribute('rows', 15);
				if (isset($moduleSettings[$type]['audio']['editor']) ? in_array('text' . $cnt, $moduleSettings[$type]['audio']['editor']) : false) {
					$form->elements['text' . $cnt]->attribute('class', 'elrte');
				}
			}
		}
		$form->submit('submit', 'Save');
		if (isset($moduleSettings[$type]['audio']['required'])) {
			foreach ($moduleSettings[$type]['audio']['required'] as $field) {
				if (isset($form->elements[$field])) {
					$form->elements[$field]->rule('required');
				}
			}
		}
		if ($id) {
			$this->template->content->title = 'Edit audio';
			$form->loadValues($audio);
		} else {
			$form->elements['file']->rule('required');
		}
		if (Request::$method == 'POST') {
			if ($form->validate()) {
				if ($id) {
					$alias = $audio['alias'];
				} else {
					$cnt = 0;
					while (true === Model_Table::instance('directoryAudio')->exists(($alias = System::random('alphanuml', 6))) && $cnt < 3) {
						$cnt++;
					}
				}
				if (isset($form->elements['file']->files[0])) {
					$files = $form->elements['file']->files;
					$file = $files[0];
					$umask = umask(0);
					$dir = $this->audioDir($alias, $section);
					if (!file_exists($dir)) {
						mkdir($dir, 0777, true);
					}
					$tmpFilename = $this->audioDir($alias, $section) . $file['name'];
					if (false === move_uploaded_file($file['tmp_name'], $tmpFilename)) {
						umask($umask);
						throw new Exception('File %s cannot be moved.');
					}
					$filename = $file['name'];
					$filesize = filesize($tmpFilename);
				}
				if ($id) {
					$values = $form->getModified();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					if (isset($filesize)) {
						$values['filesize'] = $filesize;
					}
					if (isset($filename)) {
						$values['filename'] = $filename;
					}
					Model_Table::instance('directoryAudio')->update($values, $id);
				} else {
					$values = $form->getValues();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					$values['filesize'] = $filesize;
					$values['filename'] = $filename;
					Model_Table::instance('directoryAudio')->insert($values);
				}
				$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/');
			}
		}
		$this->template->content->backUrl = Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/';
		if (isset($formError)) {
		    $form = $formError;
		}
		$this->template->content->form = $form;
	}

	private function resizeImage($alias, $section, $isCategory = false)
	{
		$moduleSettings = $this->moduleSettings[$section];
		$type = ($isCategory ? 'categories' : 'items');
		$sizes = (isset($moduleSettings[$type]['images']['sizes']) ? $moduleSettings[$type]['images']['sizes'] : array());
		if (!in_array('tiny', $sizes)) {
			$sizes[count($sizes)] = 'tiny';
		}
		if (!in_array('fullsize', $sizes)) {
			$sizes[count($sizes)] = 'fullsize';
		}
		foreach ($this->sizes as $size => $options) {
			$extension = (isset($options['options']['outputExtension']) ? $options['options']['outputExtension'] : 'jpg');
			if (count($sizes) == 0 || in_array($size, $sizes)) {
				$fileName = $this->imagePath($alias, $size, $section, $extension);
				if (!file_exists($imageDir = $this->imageDir($alias, $size, $section))) {
					mkdir($imageDir, 0777, true);
				}
				Image::Resize($this->pathImages . '_tmp/tmp', $options['size'], array_merge($options['options'], array('filename' => $fileName)));
			}
		}
	}

	private function resizeHotspot($alias, $section, $isCategory = false)
	{
		$moduleSettings = $this->moduleSettings[$section];
		$type = ($isCategory ? 'categories' : 'items');
		$sizes = (isset($moduleSettings[$type]['hotspots']['sizes']) ? $moduleSettings[$type]['hotspots']['sizes'] : array());
		if (!in_array('tiny', $sizes)) {
			$sizes[count($sizes)] = 'tiny';
		}
		foreach ($this->sizes as $size => $options) {
			$extension = (isset($options['options']['outputExtension']) ? $options['options']['outputExtension'] : 'jpg');
			if (count($sizes) == 0 || in_array($size, $sizes)) {
				$fileName = $this->hotspotPath($alias, $size, $section, $extension);
				if (!file_exists($hotspotDir = $this->hotspotDir($alias, $size, $section))) {
					mkdir($hotspotDir, 0777, true);
				}
				Image::Resize($this->pathHotspots . '_tmp/tmp', $options['size'], array_merge($options['options'], array('filename' => $fileName)));
			}
		}
	}

	private function imagePath($alias, $size, $section, $extension = 'jpg')
	{
		return $this->pathImages . $section . '/' . $size . '/' . strtolower(substr($alias, 0, 1)) . '/' . $alias . '.' . $extension;
	}

	private function imageDir($alias, $size, $section)
	{
		return $this->pathImages . $section . '/' . $size . '/' . strtolower(substr($alias, 0, 1)) . '/';
	}

	private function hotspotPath($alias, $size, $section, $extension = 'jpg')
	{
		return $this->pathHotspots. $section . '/' . $size . '/' . strtolower(substr($alias, 0, 1)) . '/' . $alias . '.' . $extension;
	}

	private function hotspotDir($alias, $size, $section)
	{
		return $this->pathHotspots . $section . '/' . $size . '/' . strtolower(substr($alias, 0, 1)) . '/';
	}

	private function attachmentPath($alias, $filename, $section)
	{
		return $this->pathAttachments . $section . '/' . strtolower(substr($alias, 0, 1)) . '/' . $alias . '/' . $filename;
	}

	private function attachmentDir($alias, $section)
	{
		return $this->pathAttachments . $section . '/' . strtolower(substr($alias, 0, 1)) . '/' . $alias . '/';
	}

	private function audioPath($alias, $filename, $section)
	{
		return $this->pathAudio . $section . '/' . strtolower(substr($alias, 0, 1)) . '/' . $alias . '/' . $filename;
	}

	private function audioDir($alias, $section)
	{
		return $this->pathAudio . $section . '/' . strtolower(substr($alias, 0, 1)) . '/' . $alias . '/';
	}

	private function videoPath($alias, $section)
	{
		return $this->pathVideos . $section . '/video/' . strtolower(substr($alias, 0, 1)) . '/' . $alias . '.flv';
	}

	private function videoDir($alias, $section)
	{
		return $this->pathVideos . $section . '/video/' . strtolower(substr($alias, 0, 1)) . '/';
	}

	private function videoPrevPath($alias, $section)
	{
		return $this->pathVideos . $section . '/preview/' . strtolower(substr($alias, 0, 1)) . '/' . $alias . '.jpg';
	}

	private function videoPrevDir($alias, $section)
	{
		return $this->pathVideos . $section . '/preview/' . strtolower(substr($alias, 0, 1)) . '/';
	}

	public function actionRemoveCategory($section, $categoryId, $internal = false)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$category = $this->model->getCategory($categoryId, $section);
		$categories = $this->model->getChidrenCategories($category['id'], $section);
		if (count($categories)) {
			foreach ($categories as $cat) {
				$this->actionRemoveCategory($section, $cat['id'], true);
			}
		}
		$items = $this->model->getCategoryItems($category['id'], $section);
		if (count($items)) {
			foreach ($items as $item) {
				$this->actionRemoveItem($section, $item['id'], true);
			}
		}
		Model_Table::instance('directoryItems')->delete((int)$category['id']);
		if (!$internal) {
			$this->response->redirect(Request::$controller . 'browse/' . $section  . '/' . $category['parentId'] . '/');
		}
	}

	public function actionRemoveItem($section, $itemId, $internal = false)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$item        = $this->model->getItem($itemId, $section);
		$images      = $this->model->getItemImages($item['id'], $section);
		$attachments = $this->model->getItemAttachments($item['id'], $section);
		$audio = $this->model->getItemAudio($item['id'], $section);
		if (count($images)) {
			foreach ($images as $image) {
				$this->actionRemoveImage($section, $image['id'], true);
			}
		}
		if (count($attachments)) {
			foreach ($attachments as $attachment) {
				$this->actionRemoveAttachment($section, $attachment['id'], true);
			}
		}
		if (count($audio)) {
			foreach ($audio as $audioItem) {
				$this->actionRemoveAudio($section, $audioItem['id'], true);
			}
		}
		Model_Table::instance('directoryItems')->delete((int)$item['id']);
		if (!$internal) {
			$this->response->redirect(Request::$controller . 'browse/' . $section  . '/' . ($item['parentId'] ? $item['parentId'] : 0) . '/');
		}
	}

	public function actionRemoveAttachment($section, $attachmentId, $internal = false)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$attachment = $this->model->getAttachment($attachmentId, $section);
		$fileName = $this->attachmentPath($attachment['alias'], $attachment['filename'], $section);
		if (file_exists($fileName)) {
			unlink($fileName);
			if (FileSystem::isDirEmpty($attDir = $this->attachmentDir($attachment['alias'], $section))) {
				rmdir($attDir);
			}
		}
		Model_Table::instance('directoryAttachments')->delete((int)$attachment['id']);
		if (!$internal) {
			$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $attachment['itemId'] . '/');
		}
	}

	public function actionRemoveAudio($section, $audioId, $internal = false)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$audio = $this->model->getAudio($audioId, $section);
		$fileName = $this->audioPath($audio['alias'], $audio['filename'], $section);
		if (file_exists($fileName)) {
			unlink($fileName);
			if (FileSystem::isDirEmpty($attDir = $this->audioDir($audio['alias'], $section))) {
				rmdir($attDir);
			}
		}
		Model_Table::instance('directoryAudio')->delete((int)$audio['id']);
		if (!$internal) {
			$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $audio['itemId'] . '/');
		}
	}

	public function actionRemoveImage($section, $imageId, $internal = false)
	{
		$moduleSettings = $this->moduleSettings[$section];
		$section = strtolower($section);
		$this->checkSection($section);
		$image = $this->model->getImage($imageId, $section);
		$sizes = $this->sizes;
		$sizes['original'] = array();
		$hotspots = $this->model->getImageHotspots($image['id'], $section);
		if (count($hotspots)) {
			foreach ($hotspots as $hotspot) {
				$this->actionRemoveHotspot($section, $hotspot['id'], true);
			}
		}
		foreach ($sizes as $size => $options) {
			$extension = (isset($options['options']['outputExtension']) ? $options['options']['outputExtension'] : 'jpg');
			$fileName = $this->imagePath($image['alias'], $size, $section, $extension);
			if (file_exists($fileName)) {
				unlink($fileName);
				if (FileSystem::isDirEmpty($imgDir = $this->imageDir($image['alias'], $size, $section))) {
					rmdir($imgDir);
				}
			}
		}
		Model_Table::instance('directoryImages')->delete((int)$image['id']);
		if (!$internal) {
			$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $image['itemId'] . '/');
		}
	}

	public function actionRemoveHotspot($section, $hotspotId, $internal = false)
	{
		$moduleSettings = $this->moduleSettings[$section];
		$section = strtolower($section);
		$this->checkSection($section);
		$hotspot = $this->model->getHotspot($hotspotId, $section);
		$sizes = $this->sizes;
		$sizes['original'] = array();
		foreach ($sizes as $size => $options) {
			$extension = (isset($options['options']['outputExtension']) ? $options['options']['outputExtension'] : 'jpg');
			$fileName = $this->hotspotPath($hotspot['token'], $size, $section, $extension);
			if (file_exists($fileName)) {
				unlink($fileName);
				if (FileSystem::isDirEmpty($hotspotDir = $this->hotspotDir($hotspot['token'], $size, $section))) {
					rmdir($hotspotDir);
				}
			}
		}
		Model_Table::instance('directoryHotspots')->delete((int)$hotspot['id']);
		if (!$internal) {
			$this->response->redirect(Request::$controller . 'hotspots/' . $section  . '/' . $hotspot['imageId'] . '/');
		}
	}

	public function actionRemoveVideo($section, $videoId, $internal = false)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$video = $this->model->getVideo($videoId, $section);
		$videoFilename = $this->videoPath($video['alias'], $section);
		if (file_exists($videoFilename)) {
			unlink($videoFilename);
			if (FileSystem::isDirEmpty($vidDir = $this->videoDir($video['alias'], $section))) {
				rmdir($vidDir);
			}
		}
		$videoPreviewFilename = $this->videoPrevPath($video['alias'], $section);
		if (file_exists($videoPreviewFilename)) {
			unlink($videoPreviewFilename);
			if (file_exists(str_ireplace('.jpg', '_.jpg', $videoPreviewFilename))) {
				unlink(str_ireplace('.jpg', '_.jpg', $videoPreviewFilename));
			}
			if (FileSystem::isDirEmpty($vidPrevDir = $this->videoPrevDir($video['alias'], $section))) {
				rmdir($vidPrevDir);
			}
		}
		Model_Table::instance('directoryVideos')->delete((int)$video['id']);
		if (!$internal) {
			$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $video['itemId'] . '/');
		}
	}
}
?>